<#import "/spring.ftl" as spring />
<#import "../layout/defaultLayout.ftl" as layout>
<@layout.defaultLayout styles=["bootstrap-table/bootstrap-table.min.css",
"bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css"]
scripts=["bootstrap-table/bootstrap-table.js",
"bootstrap-table/locale/bootstrap-table-zh-CN.min.js",
"bootstrap-validator/validator.js",
"jquery/serializejson/jquery.serializejson.min.js",
"util/jquery-dateFormat.min.js",
"bootstrap-table/extensions/export/bootstrap-table-export.min.js",
"bootstrap-datetimepicker/js/bootstrap-datetimepicker.js",
"bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js",
"Respond/respond.min.js",
"util/tableExport.js"]>
<style>
canvas {
	-moz-user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}
.chartDiv {
	border: 2px solid #ededed;
	border-radius: 10px;
	float: left;
	margin: 2 auto;
	min-width: 310px;
	background-color: white;
	height: 100%;
	margin-left: 0.5%;
	margin-top: 0.5%;
	padding: 1%;
	-webkit-border-top-left-radius: 10px;
	-webkit-border-top-right-radius: 10px;
	-webkit-border-bottom-right-radius: 10px;
	-webkit-border-bottom-left-radius: 10px
}

#container_bar {
	width: 66%;
}

#container_line {
	width: 66%;
}

#container_pie {
	width: 33%;
}
#container_button {
	width: 33%;
}
.table> tr> td, .table> th> td{
    min-width: 100px;
}
.caption-subject{
	text-align:center;
}
</style>
<div class="container-fluid">
        <div class="container">
         	 	<form class="form-inline" role="form" id="queryForm">
         	 	<input type="text" id ="reportId" name="reportId" value="${reportId}" style="display:none">
         	 	<input type="text" id ="paramStr" name="paramStr" value="${paramStr}" style="display:none">
         	 	<!-- <a  data-toggle="modal" data-target="#myModal" style="cursor:pointer;">
            		Launch modal table
        		</a> -->
                    <div>
                        <div id="main-toolbar">
			        
			          <#list reportCondition as condition>
			          	<#if condition?index%4 == 0 && condition?index != 0>
			          		<div class="col-sm-3 col-md-3">
			          	</#if>
			          	<#if condition.type == '1'>

							   <div class="form-group">
							    <label for="${condition.code}">${condition.name}</label>
							    <input type="text" class="form-control input-sm" id="${condition.code}" name="${condition.code}"/>
							  </div>
				          <#elseif condition.type == '2'>
							   <div class="form-group">
							    <label for="${condition.code}">${condition.name}</label>
							    <input type="text" id="${condition.code}" value ="" name="${condition.code}" class ="form-control input-sm datetimepicker"  />
							  </div>
						  <#elseif condition.type == '3'>

				          	 <div class="form-group">
					          <label class="control-label" for="${condition.code}">${condition.name}</label>
					            <select class="form-control input-sm" id="${condition.code}" name="${condition.code}">
					            	<option value=""><@spring.message "select.tip"/></option>
						  		<#if condition.comboboxType == 1>						  			
						  			<#list enumList as obj>
						  				<#if obj.condition.id == condition.id>
						  					<option value="${obj.code}">${obj.name}</option>
						  				</#if>
						  			</#list>
						  		<#elseif condition.comboboxType == 2>	
						  			<#if condition.cascadeCondition??>
							  			<option class="hideOption" style="display:none;" name="${condition.cascadeCondition}" code="${condition.code}"></option>
							  		<#else>
							  			<#list conditionValList as conditionVal>
							  				<#if condition.id == conditionVal.conditionId>
							  					<option value="${conditionVal.code}">${conditionVal.name}</option>
							  				</#if>
							  			</#list>
							  		</#if>
						  		</#if>
				          		</select>		
						        </div>
				          </#if>
				          <#if condition?index%4 - 3 == 0 && condition?index != 0>
			          		</div>
			          	 </#if>
			          </#list>
			          <#if reportCondition?size gt 0 >
			        	 <button id="queryByCondition" type="button" class="btn btn-success btn-sm" ><@spring.message "button.submit" /></button>
					 </#if>
					 <button id="exportExcel" type="button" class="btn btn-success btn-sm" ><@spring.message "button.export" /></button>
			      </div>
				   <div>
			<div class="main_report_dev">
				<div id="grid_data_table_dev">
					<table id="mainTable"
						data-classes="table table-hover table-striped table-condensed"
						data-toolbar="#main-toolbar" data-toggle="table"
						data-pagination="true" data-page-list="[10,20]"
						data-side-pagination="server" data-content-type="application/json"
						data-data-type="json" data-query-params-type="limit"
						data-method="post" data-height="600"
						data-response-handler="responseHandler"
						data-show-refresh="false"  data-show-columns="false" 
						data-query-params="queryParams">

					</table> 
				</div>
			</div>
		</div>
				  </form>
		
        </div>
        <div class="sub_report_dev">
        <div class="sub_report_bar caption" style="display: none">
            <i class="icon-share font-green-haze hide"></i>
            <h4 id="myModalLabel" class="caption-subject font-green bold uppercase"></h4>
            <button id="exportReport" class="btn btn-success" type="button">导出</button>
            <button id="goToReport" type="button" class="btn btn-default">返回</button>
        </div>
        <div class="sub_report_body_dev"></div>
    </div>
        

</div>

<div style="border: 0px; width: 100%">
		<div id="container_bar" hidden="true" class="chartDiv">
			<canvas id="canvas_bar"></canvas>
		</div>
		<div id="container_pie" hidden="true" class="chartDiv">
			<canvas id="canvas_pie" style="margin: 5px"></canvas>
		</div>
		<div id="container_line" hidden="true" class="chartDiv">
			<canvas id="canvas_line"></canvas>
		</div>
		<!-- <div style="margin-top: 0.5%;margin-right: 0.5%;text-align: right; float: right;" ><button onclick="toList();" class="btn btn-success" style="width: 100px;">确定</button></div>
		 -->
	</div>	
<script>	
    var mTable = $('#mainTable');
    var columns = [], datas = [], drillColumns = [];
    var flag = 0;
    var modelTable =  $('#modelTable');
    var linkItem = null;//有链接报表的字段数组
    var reportId = $('#reportId').val().replace(",","");
    var drillRequestObj = null;//点击字段传参
    var $subReportDev = $(".sub_report_dev");
    var linkReports = {};
    var currReport = {reportCode: "main", title: "主报表"};
    var reportObjs = new Array();
    var paramStr = $('#paramStr').val();
    var mainTitle = "";
    $('.datetimepicker').datetimepicker({
	    format: 'yyyy-mm-dd hh:ii:ss',
	    autoclose: true,
        todayBtn: true,
        todayHighlight:true,
        language:'zh-CN'
	});
	
	$("#queryByCondition").click(function(){
		datas = [];
		//queryData();
		freshData();
	});
	$("#goToReport").click(function () {
        //var pReport = linkReports[currReport.reportCode];
        reportObjs.pop();
        var pReport = reportObjs[reportObjs.length - 1];
        if (pReport == undefined || pReport.reportCode == 'main') {
            linkReports = {};
            currReport = {reportCode: "main", title: "主报表"};
            reportId = $('#reportId').val().replace(",","");
            showMainReport();
            document.title = mainTitle;
        }else {       	       	
            currReport = pReport;
            reportId = pReport.reportId;
            var $sub_report_item = $subReportDev.find(".sub_report_" + currReport.reportCode + "_dev");
            showSubReport($sub_report_item);
            document.title = currReport.title;
        }
    });
	
	$("#exportExcel,#exportReport").click(function(){
		
		var exportObj =  reportObjs[reportObjs.length - 1]["paramObj"];
		exportObj.reportId = reportId;
		location.href="/report/exportExcel?paramStr="+JSON.stringify(exportObj); 
		
		/* $.ajax({
	        url:'/report/exportExcel',
	        type:'post',
	        contentType: 'application/json',
	        data:JSON.stringify(exportObj),
	        dataType:'json',
	        success:function(data){
	        	
	        }
		}); */
	});
	
	function queryParams(params) {
		var mainObj = $('#queryForm').serializeJSON();
		if (paramStr){
			paramStrArray = paramStr.split(",");
			for (var i in paramStrArray){
				var paramItem = paramStrArray[i];
				var items = paramItem.split(":");
				mainObj[items[0]] = items[1];
			}
		}
		mainObj.reportId = reportId;
		reportObjs[0]["paramObj"] = mainObj;
		mainObj.offset = params.offset;
		mainObj.limit = params.limit;		
		return mainObj;
	}
	function queryDrillParams(params) {
		
		var paramObj = reportObjs[reportObjs.length - 1]["paramObj"]
		/* var objForm = $('#queryForm').serializeJSON();
		//alert(JSON.stringify(objForm))
		for (var code in objForm){
			if (typeof(paramObj[code]) == 'undefined'){
				paramObj[code] = objForm[code];
			}
		} */
		paramObj.offset = params.offset;
		paramObj.limit = params.limit;
		paramObj.reportId = reportId;
		return paramObj;
	}
	
	function responseHandler(res){
		colData = res;
		var total = colData.total;
		var dataList = colData.rows;
		var dataArray = [];
		if (dataList){
	   		 var row = null;
	   		 $.each(dataList, function(i,dataMap){  
	       		 row = {};
	       		 for (var key in dataMap){ 
	       			 xflag = 0;
	       			 for (var i in linkItem){
	       			 	if (linkItem[i] == key){
	       			 		//row[key] = "<a class='linkClass' style＝'cursor:pointer' data-toggle='modal' data-target='#myModal' name='"+key+"'>"+dataMap[key]+"</a>";
	       			 		row[key] = "<a>"+dataMap[key]+"</a>";
	       			 		xflag = 1;
	       			 		break;
	       			 	} 
	       			 }
	       			 if (xflag == 0){
	       				 row[key] = dataMap[key];
	       			 }
	       		 }
	       		dataArray.push(row);
		    });
   		}
		var retObj = new Object();
		retObj.total = total;
		retObj.rows = dataArray;
		mTable.bootstrapTable('hideLoading');
		return retObj;
	}
	
	function responseDrillHandler(res){
		colData = res;
		var total = colData.total;
		var dataList = colData.rows;
		var dataArray = [];
		if (dataList){
	   		 var row = null;
	   		 $.each(dataList, function(i,dataMap){  
	       		 row = {};
	       		 for (var key in dataMap){ 
	       			row[key] = dataMap[key];
	       		 }
	       		dataArray.push(row);
		    });
   		}
		var retObj = new Object();
		retObj.total = total;
		retObj.rows = dataArray;
		mTable.bootstrapTable('hideLoading');
		return retObj;
	}
	
	function totalTextFormatter(data) {
        return "<@spring.message 'report.sum'/>";  
    }

    function sumFormatter(data) {
        field = this.field;
        var total_sum = data.reduce(function(sum, row) {
            return (sum) + (row[field] || 0);
        }, 0);
        return total_sum;
    }
	
	function queryData(){
		mTable.bootstrapTable('showLoading');
		//alert("第几次查询："+flag);
		flag = flag + 1;
		$.ajax({
	        url:'/report/queryColumn',
	        type:'post',
	        contentType: 'application/json',
	        data:JSON.stringify({"reportId":reportId}),
	        dataType:'json',
	        success:function(data){
	        	 columns = [];
	        	linkItem = new Array();
	        	isSum = false;
	        	reportColList = data.reportColList;
	        	mainTitle = data.reportTitle;
	        	document.title = data.reportTitle;
	        	reportColumnGroupList = data.reportColumnGroupList;
	        	if (data.isSum == 1){
	        		isSum = true;
	        	}
	        	//-------------------分组------------------
	        	var mainColumns = colGrouping(reportColList,reportColumnGroupList,isSum);
	        	reportObjs[0]["column_"+currReport.reportCode] = mainColumns;
	        	if (reportColList){
		        	$.each(reportColList,function(i,item){
		        		if(flag == 1){
	        				if (item.linkReport){
	            				linkItem[linkItem.length] = item.code;    				
	            			}
	        			}
		        	});
	        	}
	        	mTable.bootstrapTable('refreshOptions',{
		        		columns:mainColumns,
		        		showFooter:isSum,
		        		url:'/report/queryData'
		        }); 
	        	
	        }
		});
	}
	
	function freshData(){
		mTable.bootstrapTable('showLoading');
		mTable.bootstrapTable('refreshOptions',{
			columns:reportObjs[reportObjs.length - 1]["column_"+currReport.reportCode],
			pageNumber:1,
    		url:'/report/queryData'
    	});
	}
	
	function queryLinkReport(xreportId, field, fn) {
        var paramObj = {};
        paramObj.reportId = xreportId;
        paramObj.colunmName = field;
        $.ajax({
            url: '/report/queryLinkReportInfo',
            type: 'post',
            contentType: 'application/json',
            data: JSON.stringify(paramObj),
            dataType: 'json',
            success: function (data) {
                fn(data);
            }
        });
    }
	function createSubReportTable(reportCode) {
        var $sub_report_item = $subReportDev.find('.sub_report_body_dev').find(".sub_report_" + reportCode + "_dev");
        if ($sub_report_item.size() == 0) {
            $sub_report_item = $('<div class="sub_report_item sub_report_' + reportCode + '_dev"></div>');
            $sub_report_item.append('<table id="sub_report_' + reportCode + '_table"' +
                    ' data-toolbar="#drillToolbar"></table>');
            $subReportDev.find('.sub_report_body_dev').append($sub_report_item);
        }
        return $sub_report_item;
    }
	function showMainReport() {
        $subReportDev.find('.sub_report_item').hide();
        $('.sub_report_bar').hide();
        $('.main_report_dev').show();
    }
    function showSubReport($sub_report_item) {
        $('.main_report_dev').hide();
        $("#myModalLabel").html(currReport.title);
        $subReportDev.find('.sub_report_item').hide();
        $('.sub_report_bar').show();
        $sub_report_item.show();
    }
	function drillReport(e, field, value, row, $element){
		//var reportId = $("#reportId").val();
        queryLinkReport(reportId, field, function (reportInfo) {
            if (reportInfo == null) return;
            var drillReportTitle = reportInfo.reportTitle;
            var linkReportColList = reportInfo.reportColList;
            var linkReportCode = reportInfo.reportCode;
            var linkReportId = reportInfo.reportId;
            var isSum = reportInfo.isSum;
            reportColumnGroupList = reportInfo.reportColumnGroupList;
            reportId = linkReportId;
           // linkReports[linkReportCode] = currReport;
           document.title = drillReportTitle;
            currReport = {reportCode: linkReportCode, title: drillReportTitle};
            linkReports[currReport.reportCode] = currReport;
            
            if (reportObjs[reportObjs.length - 1]["reportCode"] != linkReportCode){//写入报表弹出控制数组
            	reportObjs[reportObjs.length] = currReport;
            	reportObjs[reportObjs.length - 1]["reportId"] = linkReportId;
            }
            
            $("#myModalLabel").html(currReport.title);

           // $("#container_" + linkReportCode).html('');
            //$subReportDev.find('.sub_report_body_dev').html('');
            var $sub_report_item = createSubReportTable(linkReportCode);
            showSubReport($sub_report_item);

            var modelTable = $('#sub_report_' + linkReportCode + '_table');
            modelTable.bootstrapTable('showLoading');
            modelTable.on('click-cell.bs.table', function (e, field, value, row, $element) {
                drillReport(e, field, value, row, $element);
            });

            var paramObj = {};
            paramObj.reportId = linkReportId;
            paramObj.colunmName = field;
            paramObj["_" + field] = field;
            for (var key in row) {
                paramObj[key] = row[key];
            }
            var objForm = $('#queryForm').serializeJSON();
            //alert(JSON.stringify(objForm))
            for (var code in objForm) {
                //if (typeof(paramObj[code]) == 'undefined') {
                    paramObj[code] = objForm[code];
                //}
            }
            currReport["paramObj"] = paramObj;
            reportObjs[reportObjs.length - 1]["paramObj"] = paramObj;
            refreshTableAjax(linkReportColList, paramObj, modelTable, linkReportCode,isSum,reportColumnGroupList);
        });
	}
	function refreshTableAjax(reportColList, queryParam, btTable, reportCode,isSum,reportColumnGroupList) {
        var linkItem = {};
        var columns = [];
        var isShowFooter = false;
        if (isSum == 1){
        	isShowFooter = true;
        }
        
    	//-------------------分组------------------
    	columns = colGrouping(reportColList,reportColumnGroupList,isShowFooter);
        
        if (reportColList) {
            $.each(reportColList, function (i, item) {
                if (item.linkReport) {
                    //item.name = "<a  data-toggle='modal' data-target=''#myModal'>"+item.name+"</a>";
                    linkItem[item.code] = item.code;
                }
            });
        }
        btTable.bootstrapTable('destroy');
        btTable.bootstrapTable({
            height: 600,
            method: 'post',
            striped: true,
            dataType: "json",
            pagination: true,
            "queryParamsType": "limit",
            singleSelect: false,
            contentType: 'application/json',
            pageSize: 20,
            pageNumber: 1,
            search: false, //不显示 搜索框
            sidePagination: "server", //服务端请求
            queryParams: queryDrillParams,
            rowStyle: function (row, index) {
                $.each(linkItem, function (i, item) {
                   // row[item] = "<a class='linkClass' style＝'cursor:pointer' name='" + item + "'>" + row[item] + "</a>";
                    row[item] = "<a>"+row[item]+"</a>";
                });
                return row;
            },
            responseHandler: responseDrillHandler,
            showRefresh: false,
            showColumns: false, //不显示下拉框（选择显示的列）
            showExport: false,
            detailView: false,
            showPaginationSwitch: false,
            url: "/report/queryDrillData",
            columns: columns,
            showFooter:isShowFooter
        });
    }
	
	function colGrouping(reportColList,reportColumnGroupList,isSum){
		var colArray = new Array();
    	var groupColArray = new Array();
    	var hiddenColArray = new Array();
    	if (reportColList){//对分组进行封装
    		$.each(reportColList,function(i,item){
    			if (item.isHidden == 0){
    				columnObj =new Object();
    				columnObj.code = item.code;
    				columnObj.name = item.name;
    				colArray[colArray.length] =  columnObj;
    				if (reportColumnGroupList && reportColumnGroupList.length > 0){
    					$.each(reportColumnGroupList,function(j,groupItem){
        					dataColsArray = groupItem["dataCols"].split(",");
        					if ($.inArray(item.code, dataColsArray) > -1 ){
        						columnObj = {};
        						columnObj.code = groupItem.groupField;
    	        				columnObj.name = groupItem.groupName;
        					}
        				})
        				groupColArray[groupColArray.length] = columnObj;
    				}
    			}else {
    				columnObj =new Object();
    				columnObj.code = item.code;
    				columnObj.name = item.name;
    				hiddenColArray[hiddenColArray.length] = columnObj;
    			}
    		})
    	}
    	var firstLevelArray = new Array();
    	xRowspan = 0;
    	xBaseCol = {};
    	if (groupColArray){//循环第一层
    		$.each(groupColArray,function(i,item){
    			if (groupColArray[i].code == colArray[i].code){
    				if (xRowspan != 0){
    					firstLevelArray.push({
	                        field: xBaseCol.code,                   
	                        title: xBaseCol.name,
	                        visible:true,
	                        colspan: xRowspan,
	                        halign:"center"
	                    });
    					xRowspan = 0;
    		        	xBaseCol = {};
    				}
    				
    				if (isSum){
    					if (i == 0){
    						firstLevelArray.push({
    							field: groupColArray[i].code,                   
    	                        title: groupColArray[i].name,
    	                        visible:true,
    	                        rowspan: 2,
    	                        halign:"center",
    	                        footerFormatter:totalTextFormatter
    	                    });
    					}
    				}else {
    					firstLevelArray.push({
                            field: groupColArray[i].code,                   
                            title: groupColArray[i].name,
                            visible:true,
                            halign:"center",
                            rowspan: 2
                        });
    				}
    				
    				
    			}else {
    				if (xRowspan != 0){
    					if (xBaseCol.code == groupColArray[i].code){
    						xRowspan += 1;
    					}else{
    						firstLevelArray.push({
		                        field: xBaseCol.code,                   
		                        title: xBaseCol.name,
		                        visible:true,
		                        colspan: xRowspan,
		                        halign:"center"
		                    });
    						xRowspan = 1;
    						xBaseCol = groupColArray[i];
    					}
    				}else {
    					xRowspan = 1;
    		        	xBaseCol = groupColArray[i];
    				}
    				if (i == groupColArray.length - 1){//第一行最后一个
    					firstLevelArray.push({
	                        field: xBaseCol.code,                   
	                        title: xBaseCol.name,
	                        visible:true,
	                        colspan: xRowspan,
	                        halign:"center"
	                    });
    				}
    			}
    		})
    	}
    	var secondLevelArray = new Array();
    	if (colArray){//循环第二层
    		$.each(colArray,function(i,item){
    			if (groupColArray[i] != colArray[i]){
    				if (isSum){
    					if (i == 0){
    						secondLevelArray.push({
    	                        field: colArray[i].code,                   
    	                        title: colArray[i].name,
    	                        visible:true,
    	                        halign:"center",
    	                        footerFormatter:totalTextFormatter
    	                    });
    					}else {
    						secondLevelArray.push({
    	                        field: colArray[i].code,                   
    	                        title: colArray[i].name,
    	                        visible:true,
    	                        halign:"center",
    	                        footerFormatter:sumFormatter
    	                    });
    					}
    				}else {
    					secondLevelArray.push({
	                        field: colArray[i].code,                   
	                        title: colArray[i].name,
	                        visible:true,
	                        halign:"center"
	                    });
    				}
    				
    			}
    		})
    	}
    	if (hiddenColArray){//循环第二层隐藏字段
    		$.each(hiddenColArray,function(i,item){
    			if (isSum){
    				secondLevelArray.push({
                        field: hiddenColArray[i].code,                   
                        title: hiddenColArray[i].name,
                        visible:false,
                        footerFormatter:sumFormatter
                    });
    			}else {
    				secondLevelArray.push({
                        field: hiddenColArray[i].code,                   
                        title: hiddenColArray[i].name,
                        visible:false
                    });
    			}
    			
    		})
    	}
    	var mainCols = new Array();
    	mainCols[0] = firstLevelArray;
    	mainCols[1] =secondLevelArray;
    	if (secondLevelArray && firstLevelArray.length == 0){
    		return secondLevelArray;
    	}
    	return mainCols;
	}
	
    $(function () {
    	var reportId = $('#reportId').val().replace(",","");
    	//reportId = reportId.replace(",","");
    	//$('#reportId').val(reportId);
    	linkReports[currReport.reportCode] = currReport;
    	reportObjs[0] = currReport;
    	reportObjs[0]["reportId"] = reportId;
    	if (flag == 0){
    		queryData();
    	}
    	//loadCharts();   	

    	mTable.on('click-cell.bs.table', function (e,field, value, row, $element) {  
    		drillReport(e, field, value, row, $element);
    	});
    	$("select").change(function(){
    		selectId = $(this).attr('id');
    		options = $("option.hideOption").attr('name');
    		linkCode = $("option.hideOption").attr('code');
    		//reportId = $("#reportId").val();
    		for (var i in options){
    			if (selectId == options[i]){
    				$.ajax({
    	    	        url:'/report/queryConditionVal',
    	    	        type:'post',
    	    	        contentType: 'application/json',
    	    	        data:JSON.stringify({"reportId":$("#reportId").val().replace(",",""),"paramName":selectId,"paramValue":$(this).val(),"linkCode":linkCode}),
    	    	        dataType:'json',
    	    	        success:function(data){
    	    	        	$.each(data, function(i,dataMap){
    	    	        		 $("select."+linkCode).append("<option value='"+dataMap.code+"'>"+dataMap.name+"</option>");
    	    	        		
    	    		            });
    	    	        }
    	    		});
    			}
    		}
    	});

    })
    

</script>
</@layout.defaultLayout>